<!--
 * @Author: gitee 1758024667@qq.com
 * @Date: 2023-02-28 16:04:45
 * @LastEditors: gitee 1758024667@qq.com
 * @LastEditTime: 2023-03-08 00:32:36
 * @FilePath: \parking-lot-management\src\views\coupon\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<!--
 * @Author: gitee 1758024667@qq.com
 * @Date: 2023-02-28 16:04:45
 * @LastEditors: gitee 1758024667@qq.com
 * @LastEditTime: 2023-03-06 15:21:36
 * @FilePath: \parking-lot-management\src\views\coupon\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<!--
 * @Author: gitee 1758024667@qq.com
 * @Date: 2023-01-15 20:44:19
 * @LastEditors: gitee 1758024667@qq.com
 * @LastEditTime: 2023-02-24 10:53:51
 * @FilePath: \parking-lot-management\src\views\order\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div>
    <!-- 表单 -->
    <el-form :inline="true" :model="formInline" class="demo-form-inline" style="margin-left: 10px;margin-top: 20px;">
      <el-form-item label="图片名称">
        <el-input v-model="formInline.name" placeholder="名称"></el-input>
      </el-form-item>
      
      <el-form-item label="图片状态">
        <!-- 状态选择器 -->
        <el-select v-model="formInline.status" clearable placeholder="请选择">
          <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <!-- 查询 -->
      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
      </el-form-item>
      <!-- 添加 -->
      <el-form-item>
        <el-button type="primary" @click="openForm">添加图片</el-button>
      </el-form-item>
    </el-form>


    <!-- 列表可编辑 -->
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="name" label="图片名称" style="width: 10%">
      </el-table-column>
      <el-table-column prop="icon" label="图片">
        <template #default="{ row }">
          <img :src="row.icon" style="max-height: 100px" />
        </template>
      </el-table-column>
      </el-table-column>
      <el-table-column prop="status" label="状态" style="width: 10%">
      </el-table-column>
      <el-table-column fixed="right" label="操作" style="width: 10%">
        <template slot-scope="scope">
          <el-button @click="deleteData(scope.row.id)" type="text" size="small">删除</el-button>
          <el-button @click="editData(scope.row)" type="text" size="small">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--分页 -->
    <el-pagination background layout="prev, pager, next" :total=this.total style="padding: 30px 0; text-align: center;"
      @current-change="changeCurrentPage">
    </el-pagination>

    <!-- 添加优惠券的form表单 -->
    <el-dialog  title="添加或修改图片数据" :visible.sync="dialogFormVisible">
      <el-form ref="parkingLotForm" :model="form">
        <el-form-item label="图片名称" :label-width="formLabelWidth" prop="name">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <UploadImages @getImg="getImg"></UploadImages>
          <!-- <el-upload
            action="#"
            :file-list="fileList"
            list-type="picture-card"

            :on-change="onChange"
            :on-remove="onRemove"
            :on-success="handleSuccess"
            :http-request="upload"
            :before-upload="beforeUpload"
          >
            <i class="el-icon-plus" />
          </el-upload> -->
        </el-form-item>
        </el-form-item>
        <el-form-item label="图片状态" :label-width="formLabelWidth" prop="status">
          <el-select v-model="form.status" placeholder="请选择图片状态">
            <el-option label="可用图片" value="1"></el-option>
            <el-option label="失效图片" value="0"></el-option>
          </el-select>
        </el-form-item>
        <!-- 确认按键 -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitOrChangeForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { queryByConForPage, deleteById, insertCarouselChart, updateCarouselChart } from '@/api/rotationChart.js'
/*
 *@Date: 2023-01-14 22:06:37
 *@Description: 模块描述
*/
import COS from 'cos-js-sdk-v5'
// 实例化cos对象
const cos = new COS({
  SecretId: 'AKIDJQIuHOFrDTqDPM5aqreCVcV9XfX95sQm',
  SecretKey: 'DCwRkphKlzzlIchXBcqqbBXgcKn1ziDT'
})
export default {
  name: '',

  data() {
    return {
      value1: '',
      value2: '',
      // 弹窗参数
      formLabelWidth: '120px',
      dialogTableVisible: false,
      dialogFormVisible: false,
      // 绑定添加和删除表单，用于清除
      form: {
        id:'',
        name:'',
        icon:'',
        status:''
      },
      // 页面参数
      tableData: [{}],
      total: 0,
      formInline: {},
      statusOptions: [{
        value: '1',
        label: '可用图片'
      }, {
        value: '0',
        label: '废弃图片'
      }]
    }
  },
  created() {
    this.init()
  },
  mounted() { },
   
  methods: {
    getImg(img){
      console.log('上传成功===========',img);
      this.form.icon = img;
    },

   

    onRemove(file, newFileList) {
      // 手动添加双向绑定
      this.fileList = newFileList
    },
    onChange(file, newFileList) {
      this.fileList = newFileList
    },

    upload(params) {
      console.log('自定义上传函数逻辑', params)
      // 使用腾讯云
      cos.putObject({
        Bucket: 'hr-82-1313461937', /* 填入您自己的存储桶，必须字段 */
        Region: 'ap-nanjing', /* 存储桶所在地域，例如ap-beijing，必须字段 */
        Key: params.file.name, /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
        Body: params.file, /* 必须，上传文件对象，可以是input[type="file"]标签选择本地文件后得到的file对象 */
        onProgress: function(progressData) {
          console.log(JSON.stringify(progressData))
        }
      }, (err, data) => {

        console.log("=================================")
        console.log(data.Location)
        this.form.icon = data.Location
        console.log(this.form.icon)
        if (!err) {
          // 上传后处理
          this.fileList[0] // 图片只有一张时
          console.log("=================================")
          console.log(this.fileList[0])
          // 多张图片时
          // this.fileList.forEach(image => {
          //   //  要找到和储存桶的id 一样
          //   if (image.uid === params.file.uid) {
          //     // 才能更新图片地址
          //     image.url = 'http://' + data.Location
          //   }
          // })
        }
      })
    },

    // handleSuccess(response) {
    //   const imageUrl = response.data;
    //   this.form.icon.push({ icon });
    // },
    beforeUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG && !isPNG) {
        this.$message.error("上传图片只能是 JPG/PNG 格式!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
        return false;
      }
    },

    // 提交或者修改表单
    async submitOrChangeForm(){
      this.dialogFormVisible = false
      if(this.form.id == ''){
        console.log('添加轮播图')
        console.log(this.form.icon)
        await insertCarouselChart(this.form)
        this.onSubmit()
      }else{
        console.log('修改轮播图')
        console.log(this.form)
        this.changeTypeAndStatus()
        await updateCarouselChart(this.form)
        this.onSubmit()
        // this.form.id = ''
      }
    },
    // 修改状态和类型，用于后端修改
    changeTypeAndStatus(){
      if(this.form.status == '可用轮播图'){
        this.form.status = '1'
      }else if(this.form.status == '废弃轮播图'){
        this.form.status = '0'
      }
      
    },
    // 编辑表单
    editData(data){
      this.dialogFormVisible = true
      this.form = JSON.parse(JSON.stringify(data))
      console.log(this.form)
      console.log(this.formInline)
    },
    // 打开添加表单
    openForm(){
      this.dialogFormVisible = true
      this.$nextTick(()=>{
        this.$refs.parkingLotForm.resetFields();
      })
     
    },
    // 打开确认框
     deleteData(data) {
      this.$confirm('此操作将永久删除该图片, 是否确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
        deleteById(data)
        this.onSubmit()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 初始化表格
    async init() {
      const result = await queryByConForPage({})
      const res = result.data.data.records
      res.forEach(element => {
        element.status = this.changeStatus(element.status)
      })
      console.log(res)
      this.tableData = res
      this.total = result.data.data.total

    },

    // 分页查询
    async onSubmit() {
      const res = await queryByConForPage(this.formInline)
      const result = res.data.data.records
      result.forEach(element => {
        element.status = this.changeStatus(element.status)
      })
      this.total = res.data.data.total
      this.tableData = result
    },

    // 修改页
    async changeCurrentPage(page) {
      this.formInline.pageCount = page
      this.onSubmit()
    },

    // 更改状态函数
    changeStatus(key) {
      if (key == '1') {
        return '可用轮播图'
      } else if (key == '0') {
        return '废弃轮播图'
      } 
    },

  }
}
</script>

<style lang="scss" scoped></style>
